package com.example.wanandroid.activity.main.home

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.example.wanandroid.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {
    companion object {
        fun newInstance() = HomeFragment()
    }

    private lateinit var binding: FragmentHomeBinding
    private lateinit var viewModel: HomeViewModel
    private val adapter=HomeAdapter()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater,container,false)
        binding.homeList.layoutManager = LinearLayoutManager(this.context,LinearLayoutManager.VERTICAL,false)
        binding.homeList.adapter = adapter
        binding.homeList.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    val totalItemCount = layoutManager.getItemCount()
                    val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                    // 滑动到了最后一项
                    if (totalItemCount > 0 && lastVisibleItemPosition >= totalItemCount - 1) {
                        viewModel.getMoreArticleData()
                    }
                }
            }
        })
        adapter.setFragment(this)

        binding.swipeRefresh.setColorSchemeColors(Color.BLUE)
        binding.swipeRefresh.setOnRefreshListener {
            viewModel.getArticleData()
        }
        return binding.root
    }

    @Deprecated("Deprecated in Java")
    @SuppressLint("NotifyDataSetChanged")
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]
        viewModel.bannerLiveData.observe(viewLifecycleOwner){
            adapter.setBanners(it.data)
            adapter.notifyDataSetChanged()
        }
        viewModel.articlesLiveData.observe(viewLifecycleOwner){
            if(binding.swipeRefresh.isRefreshing){
                binding.swipeRefresh.isRefreshing = false
            }
            adapter.setArticles(it)
            adapter.notifyDataSetChanged()
        }

        viewModel.getBannerData()
        viewModel.getArticleData()

    }

}